package baidu;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Qiandao {
	private String auth = null;
	private String uid = null;
	private String ssid = null;
	private String preString = null;
	HttpRequester request = new HttpRequester();
	// 存放验证码的图片
	private byte[] vc_png = new byte[0];
	private Document $;
	private String lasthtml = null;
	// 用于存储某个用户所有的贴吧
	private List<String> tiebas = new ArrayList<String>();
	public String login(String user, String pwd) throws Exception {
		// do something useful with the response body
		// and ensure it is fully consumed
		HttpRespons hr = request.sendGet("http://wappass.baidu.com/wp/login?uname_login=1");
		if (loginResult(hr.content) == "2") {
			return "2";
		}
		Map<String, String> params = formdata(user, pwd, hr.content);
		HttpRespons Loginresult = request.sendPost("http://wappass.baidu.com/passport/login", params);
		return loginResult(Loginresult.content);
	}
	public String login(String user, String pwd, String verifycode) throws Exception {
		Map<String, String> params = formdata(user, pwd, lasthtml);
		params.put("verifycode", verifycode);
		params.remove("changevcode");
		HttpRespons Loginresult = request.sendPost("http://wappass.baidu.com/passport/login", params);
		return loginResult(Loginresult.content);
	}
	// 如果登录成功，返回0，登录需要验证码，返回2，密码有误返回4.帐号不存在，返回5.其他原因登录失败，返回1.
	public String loginResult(String html) {
		$ = Jsoup.parse(html);
		lasthtml = html;
		if (html.trim().equals("")) {
			try {
				html = request.sendGet("http://wapp.baidu.com").content;
				$ = Jsoup.parse(html);
				String temp = $.select("div[class=my_love_bar] a").get(0).attr("href");
				preString = temp.substring(0, temp.indexOf("m?kw="));
				System.out.println(preString);
			} catch (IOException e) {
				e.printStackTrace();
				return "1";
			}
			return "0";
		}
		if (html.indexOf("密码有误") != -1) {
			return "4";
		}
		if (html.indexOf("帐号不存在") != -1) {
			return "5";
		}
		if (html.indexOf("verify") != -1) {
			// 获取图片的路径
			String src = $.select("form[action=/passport/login] img").attr("src");
			try {
				vc_png = request.sendGet(src).data;
			} catch (IOException e) {
				e.printStackTrace();
			}
			return "2";
		}
		try {
			html = request.sendGet("http://wapp.baidu.com").content;
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(html);
		auth = mid(html, "auth=", "&");
		uid = mid(html, "uid=", "&");
		ssid = mid(html, "ssid=", "\"");
		return auth != null && uid != null && ssid != null ? "0" : "1";
	}
	public Map<String, String> formdata(String user, String pwd, String content) {
		Map<String, String> result = new LinkedHashMap<String, String>();
		Document doc = Jsoup.parse(content);
		Elements mods = doc.getElementsByClass("mod-content");
		if (mods.size() != 1) {
			try {
				content = request.sendGet("http://wappass.baidu.com/wp/login?uname_login=1").content;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			doc = Jsoup.parse(content);
			mods = doc.getElementsByClass("mod-content");
		}
		Elements list = mods.get(0).getElementsByTag("input");
		for (Element e : list) {
			if (e.attr("name").equalsIgnoreCase("username")) {
				result.put("username", user);
			} else if (e.attr("name").equalsIgnoreCase("password")) {
				result.put("password", pwd);
			} else
				result.put(e.attr("name"), e.attr("value"));
		}
		return result;
	}
	// 进入指定的贴吧页面，找到签到的链接并调用post实现点击操作。
	public boolean qiandao(String kw) {
		// http://tieba.baidu.com/mo/q---80208365781BB0704EF105472C64363D--1-1-0--2--80208365781BB0704EF105472C64363D/m?kw=%E5%AE%8C%E7%BE%8E%E4%B8%96%E7%95%8C&lp=1030
		// http://tieba.baidu.com/mo/q---80208365781BB0704EF105472C64363D--1-1-0--2--80208365781BB0704EF105472C64363D/sign?tbs=b78a46b08506fd121379756992&fid=512139&kw=%E5%AE%8C%E7%BE%8E%E4%B8%96%E7%95%8C
		// http://tieba.baidu.com/mo/q---80208365781BB0704EF105472C64363D--1-1-0--2--80208365781BB0704EF105472C64363D/m?kw=%E8%87%B4%E5%91%BD%E6%AD%A6%E5%8A%9B%E4%B9%8B%E6%96%B0%E4%B8%96%E7%95%8C&ie=utf-8&lp=1030
		String tieba = null;
		try {
			tieba = request.sendGet(preString + "m?kw=" + kw + "&lp=1030").content;
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (tieba != null && tieba.contains("已签到")) {
			return true;
		}
		Document tieba$ = Jsoup.parse(tieba);
		String href = "";
		Elements select = tieba$.select("a:contains(签到)");
		if (select == null) {
			return false;
		}
		href = select.attr("href");
		if (href == null || href.length() == 0) {
			return false;
		}
		String html = "";
		try {
			html = request.sendGet("http://wapp.baidu.com/" + href).content;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return html.indexOf("签到成功") != -1;
	}
	// 获取所有的贴吧
	public void getTieBas() {
		try {
			String href = $.select("meta[http-equiv=refresh]").attr("content");
			if (href == null || href.length() == 0) {
				return;
			}
			href = href.substring(6, href.length());
			String html = request.sendGet(href).content;
			$ = Jsoup.parse(html);
			String moreHref = $.select("a:contains(我爱逛的贴吧)").attr("href");
			html = request.sendGet("http://wapp.baidu.com/" + moreHref).content;
			$ = Jsoup.parse(html);
			Elements as = $.select("table a");
			for (Element element : as) {
				String attr = element.attr("href");
				if (attr == null || attr.length() == 0 || !attr.contains("m?kw=")) {
					continue;
				}
				try {
					attr = URLDecoder.decode(attr, "utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				getTiebas().add(attr.substring(5));
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	/**
	 * 取文本之间
	 * 
	 * @param value
	 *            字符串
	 * @param left
	 *            左边
	 * @param right
	 *            右边
	 * @return 中间子串
	 */
	public static String mid(String value, String left, String right) {
		if (value.indexOf(left) == -1) {
			return null;
		}
		try {
			int index = value.indexOf(left) + left.length();
			return value.substring(index, value.indexOf(right, index));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public byte[] getVc_png() {
		return vc_png;
	}
	public void setVc_png(byte[] vc_png) {
		this.vc_png = vc_png;
	}
	public List<String> getTiebas() {
		if (tiebas.size() == 0) {
			getTieBas();
		}
		return tiebas;
	}
	public void setTiebas(List<String> tiebas) {
		this.tiebas = tiebas;
	}
}
